package cn.zc.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import lombok.extern.slf4j.Slf4j;
import cn.zc.entity.User;
import cn.zc.mapper.LoginMapper;
import cn.zc.properties.JwtProperties;

import java.util.Enumeration;

@Component
@Slf4j
public class AdminInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private LoginMapper loginMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            // 当前拦截到的不是动态方法，直接放行
            return true;
        }
        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getStudentTokenName());
        if (token == null|| token.isEmpty()||token.equals("null")){
            response.setStatus(401);//TODO 密钥失效，请联系管理员
            response.getWriter().write("-3");
            return false;
        }
        User user = loginMapper.getUserByUUID(token);
        if(user==null){
            response.getWriter().write("-1");
            response.setStatus(401);
            return false;
        }
        String id = request.getParameter("id");
        if(user.getId().equals(id)){
            response.getWriter().write("-2");
            response.setStatus(401);
            return false;
        }
        return true;
    }
}